﻿using System;
using System.Net;
using System.Threading;
using System.Net.Sockets;
using System.Collections.Generic;

//自定义命名空间
using DreamCube.Foundation.Basic.Utility;

namespace WebServer.Service.BLL
{
    public static class Utility
    {
        ///// <summary>
        ///// 根据绑定对象生成前缀
        ///// </summary>
        ///// <param name="binding"></param>
        ///// <returns></returns>
        //public static String WebBindingToPrefix(Model.WebBinding binding)
        //{
        //    if (binding.Port == 80)
        //        return String.Format("{0}://{1}/", binding.Protocol, binding.Hostname);
        //    else
        //        return String.Format("{0}://{1}:{2}/", binding.Protocol, binding.Hostname, binding.Port);
        //}

        /// <summary>
        /// 获取本地服务器的Url前缀
        /// </summary>
        /// <param name="port">端口号</param>
        /// <returns></returns>
        public static String[] GetLocalHostPrefix(Int32 port = 80)
        {
            String hostName = Dns.GetHostName();
            String[] ipAddresses = MyNet.GetIPAddressEx(AddressFamily.InterNetwork, "", true);
            List<String> prefixs = new List<String>();
            for (Int32 i = 0; i < ipAddresses.Length; i++)
            {
                if (port == 80)
                    prefixs.Add(String.Format("http://{0}/", ipAddresses[i]));
                else
                    prefixs.Add(String.Format("http://{0}:{1}/", ipAddresses[i], port.ToString()));
            }
            return prefixs.ToArray();
        }

        /// <summary>
        /// 获取网站的默认文档名
        /// </summary>
        /// <returns></returns>
        public static String[] GetDefualtDocuments()
        {
            String[] defaultDocuments = { "default.aspx", "default.htm", "default.html", "index.htm", "index.html" };
            return defaultDocuments;
        }

        /// <summary>
        /// 获取禁止浏览的目录名称
        /// </summary>
        /// <returns></returns>
        public static String[] GetDefaultRestrictedDirs()
        {
            String[] restrictedDirs = { "/bin", "/app_browsers", "/app_code", "/app_data", "/app_localresources", "/app_globalresources", "/app_webreferences" };
            return restrictedDirs;
        }

        /// <summary>
        /// 格式化虚拟目录，把目录格式化成统一的虚拟目录格式，虚拟目录格式统一为：/path；
        /// 也就是字符串的前面有反斜杠符，并且所有符号均是反斜杠符号，没有斜杠符
        /// </summary>
        /// <param name="virtualPath"></param>
        /// <returns></returns>
        public static String FormatVirtualPath(String virtualPath)
        {
            if (virtualPath.IsNullOrEmpty())
                return "/";
            virtualPath = virtualPath.Replace("\\", "/");
            if (!virtualPath.StartsWith("/"))
                virtualPath = "/" + virtualPath;
            return virtualPath;
        }

        /// <summary>
        /// 格式化HttpListener监听的Url串，串必须是以反斜杠（"/"）结尾，并且不能包含斜杠符号
        /// </summary>
        /// <param name="prefix"></param>
        /// <returns></returns>
        public static String FormatHttpListenerPrefix(String prefix, Int32 port)
        {
            if (prefix.IsNullOrEmpty())
                return prefix;
            prefix = prefix.Replace("\\", "/");
            if (!prefix.EndsWith("/"))
                prefix += "/";
            if (port != 80)
            {
                String portStr = String.Format(":{0}", port);
                //判断url是否包含了端口号
                if (prefix.IndexOf(portStr) < 0)
                    prefix = prefix.LeftOfLast("/") + portStr + "/";
            }
            return prefix;
        }

        /// <summary>
        /// 格式化HttpListener监听的Url串，串必须是以反斜杠（"/"）结尾，并且不能包含斜杠符号
        /// </summary>
        /// <param name="prefixs"></param>
        /// <returns></returns>
        public static String[] FormatHttpListenerPrefix(String[] prefixs, Int32 port)
        {
            if (prefixs == null || prefixs.Length == 0) return null;
            for (Int32 i = 0; i < prefixs.Length; i++)
                prefixs[i] = FormatHttpListenerPrefix(prefixs[i], port);
            return prefixs;
        }

        /// <summary>
        /// 根据请求的上下文验证请求的Url是否合法
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static Boolean ValidateRequestUrl(HttpListenerContext context)
        {
            String url = context.Request.RawUrl.ToString();
            if (url.IndexOf(".") > -1)
            {
                if (!url.EndsWith("/"))
                    return true;
                else
                {
                    ThreadPool.QueueUserWorkItem((obj) =>
                    { context.Response.Redirect(context.Request.Url.ToString().LeftOfLast("/")); context.Response.Close(); });
                    return false;
                }
            }

            if (!url.EndsWith("/"))
            {
                ThreadPool.QueueUserWorkItem((obj) =>
                { context.Response.Redirect(context.Request.Url.ToString() + "/"); context.Response.Close(); });
                return false;
            }
            return true;
        }

        /// <summary>
        /// 格式化物理路径
        /// </summary>
        /// <param name="physicalPath"></param>
        /// <returns></returns>
        public static String FormatPhysicalPath(String physicalPath)
        {
            if (physicalPath.IsNullOrEmpty())
                return String.Empty;

            physicalPath = physicalPath.Replace("/", "\\");

            if (!physicalPath.EndsWith("\\"))
                physicalPath += "\\";
            return physicalPath;
        }
    }
}
